package com.simpletour.qa.common.util;

import lombok.extern.slf4j.Slf4j;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author zhaohw
 * @date 2018-06-21 16:23
 * @email zhaohongwei@simpletour.com
 */
@Slf4j
public class ReflectionUtils {

    /**
     * 将id值写入Entity中@id注解字段
     * @param entity
     * @param id
     * @throws IntrospectionException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    public static void setPrimaryKey(Object entity,Object id)
            throws IntrospectionException, InvocationTargetException, IllegalAccessException {
        Class clazz = entity.getClass();
        List<Field> list = new ArrayList<Field>();
        list = getDeclaredFieldsWithSuperClass(list,clazz);
        for (Field field : list){
            if(field.getAnnotation(javax.persistence.Id.class)!=null){
                PropertyDescriptor pd = new PropertyDescriptor(field.getName(),clazz);
                Class type = field.getType();
                Method setMethod = pd.getWriteMethod();
                setMethod.invoke(entity,id);
            }
        }
    }


    private static List<Field> getDeclaredFieldsWithSuperClass(List<Field> fields,Class clazz){
        //传入Object 的class直接返回
        if(Object.class.getName().equals(clazz.getName())){
            return fields;
        }
        Field[] fieldArr = clazz.getDeclaredFields();
        fields.addAll(Arrays.asList(fieldArr));
        if(!Object.class.getName().equals(clazz.getSuperclass().getName())){
            getDeclaredFieldsWithSuperClass(fields,clazz.getSuperclass());
        }
        return fields;

    }

}
